<script lang="ts">
import { FInput } from 'fok-ui';
import { PropType, defineComponent, h, watch, resolveComponent } from 'vue';

export default defineComponent({
  name: 'f-dy-inputs',
  props: {
    fields: Array as PropType<{ field: string; editType: string }[]>,
    value: Object as PropType<{ [x: string]: string }>
  },
  emits: ['update:value', 'change'],
  setup: (props, { emit }) => {
    const notify = (value) => {
      emit('update:value', value);
      emit('change', value);
    };
    watch(
      () => props.value,
      (v) => {
        if (!v) {
          notify(
            props.fields!.reduce((a, item) => ({
              ...a,
              [item.field]: ''
            }))
          );
        }
      },
      { immediate: true }
    );

    return () => {
      return h(
        'div',
        { class: 'flex' },
        props.fields?.map((item, index) => {
          const Comp = item.editType ? resolveComponent(item.editType) : FInput;
          return [
            h(Comp as any, {
              value: props.value?.[item.field],
              'onUpdate:value': (v) => {
                const obj = { ...props.value };
                obj[item.field] = v;
                notify(obj);
              }
            }),
            index != props.fields!.length - 1 && h('span', { class: 'mx2' }, '/')
          ];
        })
      );
    };
  }
});
</script>
